Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

POC: to batch plugin responses this has reduced webworker scripting by 2 seconds #37762

Draft
wants to merge 2 commits into
base: release
Choose a base branch
from

Conversation

vsvamsi1
Copy link
Contributor

@vsvamsi1 vsvamsi1 commented Nov 26, 2024

batching updateAction Data basically batching the results of plugin responses

Description

Tip

Add a TL;DR when the description is longer than 500 words or extremely technical (helps the content, marketing, and DevRel team).

Please also include relevant motivation and context. List any dependencies that are required for this change. Add links to Notion, Figma or any other documents that might be relevant to the PR.

Fixes #Issue Number
or
Fixes Issue URL

Warning

If no issue exists, please create an issue first, and check with the maintainers if the issue is valid.

Automation

/ok-to-test tags="@tag.All"

🔍 Cypress test results

Caution

🔴 🔴 🔴 Some tests have failed.
Workflow run: https://github.com/appsmithorg/appsmith/actions/runs/12056385315
Commit: 9bd05ce
Cypress dashboard.
Tags: @tag.All
Spec:
The following are new failures, please fix them before merging the PR:

  1. cypress/e2e/Regression/Apps/CommunityIssues_Spec.ts
  2. cypress/e2e/Regression/Apps/ImportExportForkApplication_spec.js
  3. cypress/e2e/Regression/Apps/MongoDBShoppingCart_spec.ts
  4. cypress/e2e/Regression/ClientSide/ActionExecution/NavigateTo_spec.ts
  5. cypress/e2e/Regression/ClientSide/Autocomplete/JS_AC1_spec.ts
  6. cypress/e2e/Regression/ClientSide/Binding/TableTextPagination_spec.js
  7. cypress/e2e/Regression/ClientSide/Binding/TableV2TextPagination_spec.js
  8. cypress/e2e/Regression/ClientSide/Binding/TableV2_Api_spec.js
  9. cypress/e2e/Regression/ClientSide/Binding/Table_Api_spec.js
  10. cypress/e2e/Regression/ClientSide/BugTests/DS_Bug28985_spec.ts
  11. cypress/e2e/Regression/ClientSide/BugTests/JS_Bug29131_spec.ts
  12. cypress/e2e/Regression/ClientSide/Debugger/Widget_property_navigation_spec.ts
  13. cypress/e2e/Regression/ClientSide/ExplorerTests/Renaming_spec.js
  14. cypress/e2e/Regression/ClientSide/Git/ExistingApps/v1.9.24/DSCrudAndBindings_Spec.ts
  15. cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/OneClickBindingMysql_spec.ts
  16. cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/Table_MongoDB_spec.ts
  17. cypress/e2e/Regression/ClientSide/OneClickBinding/TableWidget/Table_postgres_spec.ts
  18. cypress/e2e/Regression/ClientSide/PeekOverlay/PeekOverlay_Spec.ts
  19. cypress/e2e/Regression/ClientSide/Widgets/Button/Button2_spec.ts
  20. cypress/e2e/Regression/ClientSide/Widgets/ListV2/Listv2_BasicServerSideData_spec.js
  21. cypress/e2e/Regression/ClientSide/Widgets/ListV2/Listv2_Meta_Hydration_ServerSide_spec.js
  22. cypress/e2e/Regression/ClientSide/Widgets/Migration_Spec.js
  23. cypress/e2e/Regression/ClientSide/Widgets/Modal/Modal_spec.ts
  24. cypress/e2e/Regression/ClientSide/Widgets/Radio/Radio2_spec.ts
  25. cypress/e2e/Regression/ClientSide/Widgets/Select/Select3_Spec.ts
  26. cypress/e2e/Regression/ServerSide/ApiTests/API_Bugs_Spec.js
  27. cypress/e2e/Regression/ServerSide/ApiTests/API_MultiPart_Spec.ts
  28. cypress/e2e/Regression/ServerSide/GenerateCRUD/MongoURI_Spec.ts
  29. cypress/e2e/Regression/ServerSide/GenerateCRUD/MySQL2_Spec.ts
  30. cypress/e2e/Regression/ServerSide/GenerateCRUD/Postgres2_Spec.ts
  31. cypress/e2e/Regression/ServerSide/MySQL_Datatypes/Basic_Spec.ts
  32. cypress/e2e/Regression/ServerSide/OnLoadTests/OnLoadActions_Spec.ts
  33. cypress/e2e/Regression/ServerSide/Postgres_DataTypes/Array_Spec.ts
  34. cypress/e2e/Regression/ServerSide/Postgres_DataTypes/Binary_Spec.ts
  35. cypress/e2e/Regression/ServerSide/Postgres_DataTypes/BooleanEnum_Spec.ts
  36. cypress/e2e/Regression/ServerSide/Postgres_DataTypes/Character_Spec.ts
  37. cypress/e2e/Regression/ServerSide/Postgres_DataTypes/DateTime_Spec.ts
  38. cypress/e2e/Regression/ServerSide/Postgres_DataTypes/Json_Spec.ts
  39. cypress/e2e/Regression/ServerSide/Postgres_DataTypes/Numeric_Spec.ts
  40. cypress/e2e/Regression/ServerSide/Postgres_DataTypes/UUID_Spec.ts
  41. cypress/e2e/Regression/ServerSide/QueryPane/Mongo1_spec.ts
  42. cypress/e2e/Regression/ServerSide/QueryPane/S3_1_spec.js
  43. cypress/e2e/Regression/ServerSide/QueryPane/S3_2_spec.ts
  44. cypress/e2e/Sanity/Datasources/SMTPDatasource_spec.js
List of identified flaky tests.
Wed, 27 Nov 2024 19:54:36 UTC

Communication

Should the DevRel and Marketing teams inform users about this change?

  • Yes
  • No

Summary by CodeRabbit

  • New Features

    • Introduced a new mechanism for capturing action data updates within a specified 10-second window, allowing for more efficient processing of actions.
    • Added a new action type TRIGGER_EVAL_BATCH for batch evaluations, enhancing the handling of multiple evaluations in a single action.
  • Bug Fixes

    • Improved handling of action data updates by modifying the way parameters are accepted in the action handling functions.
    • Enhanced error handling during execution data processing, improving robustness.

Copy link
Contributor

coderabbitai bot commented Nov 26, 2024

Walkthrough

The changes in this pull request focus on enhancing the PluginActionSaga.ts file by implementing a new generator function, captureActionsWithinPeriod, designed to collect action data over a specified time frame. This function captures UPDATE_ACTION_DATA actions using a non-blocking approach, allowing for bulk dispatching after a 10-second window. Additionally, modifications were made to the handleUpdateActionData function to streamline parameter handling, and the watchPluginActionExecutionSagas function was updated to utilize the new capturing mechanism. Changes were also made to action constants and related files to support the new functionality.

Changes

File Path Change Summary
app/client/src/sagas/ActionExecution/PluginActionSaga.ts - Added captureActionsWithinPeriod generator function for bulk action capturing.
- Added captureActionsWithinPeriodTriggers function for evaluation management.
- Updated handleUpdateActionData to accept action object directly.
- Replaced takeEvery for UPDATE_ACTION_DATA with captureActionsWithinPeriod.
- Imported fork and race effects for new action capturing logic.
app/client/src/ce/actions/evaluationActionsList.ts - Removed ReduxActionTypes.TRIGGER_EVAL and added ReduxActionTypes.TRIGGER_EVAL_BATCH in the evaluation actions.
app/client/src/ce/constants/ReduxActionConstants.tsx - Added new action type TRIGGER_EVAL_BATCH to EvaluationActionTypes.
app/client/src/workers/Evaluation/fns/utils/TriggerEmitter.ts - Updated storeUpdatesHandler to include a return statement.
- Enhanced fnExecutionDataHandler with error handling for execution data.

Possibly related PRs

Suggested labels

Performance, Task, Bug, ok-to-test, Workflows Pod, Workflows Product

Suggested reviewers

  • ayushpahwa
  • dvj1988
  • ankitakinger

🎉 In the land of code where actions play,
A saga was born to capture the fray.
With a ten-second window, it gathers with grace,
Dispatching in bulk, keeping up the pace.
So here's to the changes, both clever and bright,
Enhancing our flow, making everything right! 🚀


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (1)
app/client/src/sagas/ActionExecution/PluginActionSaga.ts (1)

1703-1703: Remove unnecessary ESLint disable comment.

The // eslint-disable-next-line prefer-const comment appears unnecessary. Consider removing it to maintain clean code.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f41cf12 and 534fd11.

📒 Files selected for processing (1)
  • app/client/src/sagas/ActionExecution/PluginActionSaga.ts (4 hunks)
🔇 Additional comments (2)
app/client/src/sagas/ActionExecution/PluginActionSaga.ts (2)

5-5: Approved: Added necessary imports.

The inclusion of fork and race from redux-saga/effects is appropriate for the new saga functions.

Also applies to: 7-7


Line range hint 1682-1686: Approved: Updated parameters in handleUpdateActionData.

Extracting actionDataPayload and parentSpan directly from action enhances readability and aligns with the function's usage.

@@ -1703,6 +1744,6 @@ export function* watchPluginActionExecutionSagas() {
),
takeLatest(ReduxActionTypes.PLUGIN_SOFT_REFRESH, softRefreshActionsSaga),
takeEvery(ReduxActionTypes.EXECUTE_JS_UPDATES, makeUpdateJSCollection),
takeEvery(ReduxActionTypes.UPDATE_ACTION_DATA, handleUpdateActionData),
takeEvery(ReduxActionTypes.START_EVALUATION, captureActionsWithinPeriod),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Prevent multiple instances of captureActionsWithinPeriod.

Using takeEvery with captureActionsWithinPeriod may start multiple saga instances if START_EVALUATION is dispatched repeatedly. To ensure only a single instance runs, consider using takeLeading or starting the saga once.

Apply this diff to adjust the saga watcher:

 export function* watchPluginActionExecutionSagas() {
   yield all([
     takeLatest(ReduxActionTypes.RUN_ACTION_REQUEST, runActionSaga),
     takeLatest(
       ReduxActionTypes.RUN_ACTION_SHORTCUT_REQUEST,
       runActionShortcutSaga,
     ),
     takeLatest(
       ReduxActionTypes.EXECUTE_PAGE_LOAD_ACTIONS,
       executePageLoadActionsSaga,
     ),
     takeLatest(ReduxActionTypes.PLUGIN_SOFT_REFRESH, softRefreshActionsSaga),
     takeEvery(ReduxActionTypes.EXECUTE_JS_UPDATES, makeUpdateJSCollection),
-    takeEvery(ReduxActionTypes.START_EVALUATION, captureActionsWithinPeriod),
+    takeLeading(ReduxActionTypes.START_EVALUATION, captureActionsWithinPeriod),
   ]);
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
takeEvery(ReduxActionTypes.START_EVALUATION, captureActionsWithinPeriod),
export function* watchPluginActionExecutionSagas() {
yield all([
takeLatest(ReduxActionTypes.RUN_ACTION_REQUEST, runActionSaga),
takeLatest(
ReduxActionTypes.RUN_ACTION_SHORTCUT_REQUEST,
runActionShortcutSaga,
),
takeLatest(
ReduxActionTypes.EXECUTE_PAGE_LOAD_ACTIONS,
executePageLoadActionsSaga,
),
takeLatest(ReduxActionTypes.PLUGIN_SOFT_REFRESH, softRefreshActionsSaga),
takeEvery(ReduxActionTypes.EXECUTE_JS_UPDATES, makeUpdateJSCollection),
takeLeading(ReduxActionTypes.START_EVALUATION, captureActionsWithinPeriod),
]);
}

Comment on lines +1695 to +1733
// Use a channel to queue all actions

function* captureActionsWithinPeriod() {
while (true) {
const buffer = []; // Initialize a new buffer for each batch
const endTime = Date.now() + 10000;
let parentSpan;
// eslint-disable-next-line prefer-const

while (Date.now() < endTime) {
try {
// Use a non-blocking `take` to capture actions within the period

const { action } = yield race({
action: take(ReduxActionTypes.UPDATE_ACTION_DATA),
del: delay(1000),
});

if (!action) continue;

const { actionDataPayload } = action.payload;

parentSpan = action.payload.parentSpan;
buffer.push(...actionDataPayload);
} catch (e) {
// Handle errors if needed
}
}

// After the time period, dispatch the collected actions
if (buffer.length > 0) {
yield fork(handleUpdateActionData, {
parentSpan,
actionDataPayload: buffer,
});
}
}
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Refactor looping mechanism to prevent high CPU usage.

The inner loop while (Date.now() < endTime) can cause high CPU utilization due to continuous execution. Consider using a more efficient approach that waits for actions or a timeout without busy-waiting.

Apply this diff to refactor the function:

 function* captureActionsWithinPeriod() {
   while (true) {
+    const buffer = []; // Initialize a new buffer for each batch
+    let parentSpan;
+    const startTime = Date.now();
+    const endTime = startTime + 10000;
+
+    while (Date.now() < endTime) {
       try {
-        const { action } = yield race({
-          action: take(ReduxActionTypes.UPDATE_ACTION_DATA),
-          del: delay(1000),
-        });
+        const { action, timeout } = yield race({
+          action: take(ReduxActionTypes.UPDATE_ACTION_DATA),
+          timeout: delay(endTime - Date.now()),
+        });

-        if (!action) continue;
+        if (timeout) {
+          break;
+        }

         const { actionDataPayload } = action.payload;
         parentSpan = action.payload.parentSpan;
         buffer.push(...actionDataPayload);
       } catch (e) {
         // Handle errors if needed
       }
     }

     // After the time period, dispatch the collected actions
     if (buffer.length > 0) {
       yield fork(handleUpdateActionData, {
         parentSpan,
         actionDataPayload: buffer,
       });
     }
   }
 }

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (2)
app/client/src/workers/Evaluation/fns/utils/TriggerEmitter.ts (1)

Line range hint 109-116: Consider addressing the eslint TODOs.

There are multiple TODOs about fixing eslint disable directives. Since we're touching this file, it would be good to properly type the data structures instead of using any.

Would you like help with properly typing these structures to remove the eslint disable comments?

app/client/src/ce/constants/ReduxActionConstants.tsx (1)

300-300: LGTM! Consider adding JSDoc comments.

The new action type TRIGGER_EVAL_BATCH aligns well with the PR's objective of batching plugin responses. The naming follows the established convention.

Consider adding JSDoc comments to document the purpose and usage of this new action type:

/**
 * Action type for triggering batch evaluation of plugin responses.
 * Used to optimize performance by reducing webworker scripting time.
 */
TRIGGER_EVAL_BATCH: "TRIGGER_EVAL_BATCH",
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 534fd11 and 9bd05ce.

📒 Files selected for processing (4)
  • app/client/src/ce/actions/evaluationActionsList.ts (1 hunks)
  • app/client/src/ce/constants/ReduxActionConstants.tsx (1 hunks)
  • app/client/src/sagas/ActionExecution/PluginActionSaga.ts (4 hunks)
  • app/client/src/workers/Evaluation/fns/utils/TriggerEmitter.ts (1 hunks)
🔇 Additional comments (3)
app/client/src/ce/actions/evaluationActionsList.ts (1)

110-111: LGTM, but verify edge cases for batched evaluations.

The change aligns with the PR's performance optimization goals. However, since this modifies core evaluation behavior:

Let's verify other components that might expect immediate evaluation:

Consider documenting the batching behavior and any timing implications in the constants file or relevant documentation.

✅ Verification successful

Let me generate additional scripts to verify the impact of this change.

I want to check:

  1. How TRIGGER_EVAL_BATCH is being used
  2. The evaluation trigger patterns in sagas to understand the batching behavior
  3. The relationship between TRIGGER_EVAL and TRIGGER_EVAL_BATCH

This will help determine if removing TRIGGER_EVAL in favor of TRIGGER_EVAL_BATCH is safe.


LGTM - The change to use TRIGGER_EVAL_BATCH is safe

The code shows TRIGGER_EVAL_BATCH is properly implemented in PluginActionSaga.ts as a batched alternative to TRIGGER_EVAL. The remaining TRIGGER_EVAL usages are in distinct flows:

  • WidgetLoadingSaga: For widget loading evaluation
  • NavigateActionSaga: For navigation-specific evaluation

The change aligns with the PR's performance optimization goals by batching plugin responses while preserving necessary immediate evaluations in other contexts.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct dependencies on TRIGGER_EVAL
rg "TRIGGER_EVAL[^_]" --type ts

# Search for timing-sensitive evaluation patterns
ast-grep --pattern 'ReduxActionTypes.TRIGGER_EVAL'

Length of output: 152096


Script:

#!/bin/bash
# Search for TRIGGER_EVAL_BATCH usage and dependencies
rg "TRIGGER_EVAL_BATCH" --type ts -C 2

# Search for evaluation trigger patterns in sagas
rg "TRIGGER_EVAL" app/client/src/sagas/ -C 2

Length of output: 3310

app/client/src/sagas/ActionExecution/PluginActionSaga.ts (2)

1725-1762: Refactor looping mechanism to prevent high CPU usage.

Similar performance and error handling issues as captureActionsWithinPeriodTriggers.


1777-1781: Prevent multiple instances of captureActionsWithinPeriod.

Using takeEvery with both capture functions may start multiple saga instances if START_EVALUATION is dispatched repeatedly.

Comment on lines +85 to +90
const storeUpdatesHandler = priorityBatchedActionHandler((batchedData) => {
return WorkerMessenger.ping({
method: MAIN_THREAD_ACTION.PROCESS_STORE_UPDATES,
data: batchedData,
}),
);
});
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Consider adding explicit returns to other batched handlers for consistency

Found similar handlers in TriggerEmitter.ts that would benefit from explicit returns:

  • defaultTriggerHandler - currently no return statement
  • Handler in jsVariableUpdatesHandler - currently no return statement
  • Log processing handler - currently no return statement
🔗 Analysis chain

LGTM! The explicit return improves clarity.

The addition of the explicit return statement for WorkerMessenger.ping enhances code clarity and enables proper promise chaining if needed by callers.

Let's verify if other similar handlers need the same treatment:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other handlers that might benefit from explicit returns
ast-grep --pattern 'const $_Handler = priorityBatchedActionHandler((batchedData) => {
  WorkerMessenger.ping({
    $$$
  })
})'

Length of output: 129


Script:

#!/bin/bash
# Let's try a broader search for priorityBatchedActionHandler usage
rg -A 5 "priorityBatchedActionHandler" 

# Also search for similar patterns with WorkerMessenger.ping
rg -A 5 "WorkerMessenger.ping"

Length of output: 4869

Comment on lines +1678 to +1679
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function* handleUpdateActionData(action: any) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add proper TypeScript types instead of using 'any'.

Define an interface for the action parameter instead of using 'any' to maintain type safety.

-function* handleUpdateActionData(action: any) {
+interface UpdateActionDataPayload {
+  actionDataPayload: Array<{
+    entityName: string;
+    dataPath: string;
+    data: unknown;
+  }>;
+  parentSpan?: OtlpSpan;
+}
+function* handleUpdateActionData(action: UpdateActionDataPayload) {

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +1693 to +1723
function* captureActionsWithinPeriodTriggers() {
while (true) {
const buffer = []; // Initialize a new buffer for each batch
const endTime = Date.now() + 10000;
// eslint-disable-next-line prefer-const

while (Date.now() < endTime) {
try {
// Use a non-blocking `take` to capture actions within the period

const { action } = yield race({
action: take(ReduxActionTypes.TRIGGER_EVAL),
del: delay(1000),
});

if (!action) continue;

buffer.push(action);
} catch (e) {
// Handle errors if needed
}
}

// After the time period, dispatch the collected actions
if (buffer.length > 0) {
yield put({
type: ReduxActionTypes.TRIGGER_EVAL_BATCH,
});
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve performance and error handling.

The function has two issues:

  1. The busy-waiting loop can cause high CPU usage
  2. Empty catch block could hide important errors
 function* captureActionsWithinPeriodTriggers() {
   while (true) {
     const buffer = [];
-    const endTime = Date.now() + 10000;
+    const BATCH_WINDOW = 10000;
+    const batchStart = Date.now();

-    while (Date.now() < endTime) {
+    while (Date.now() - batchStart < BATCH_WINDOW) {
       try {
         const { action } = yield race({
           action: take(ReduxActionTypes.TRIGGER_EVAL),
-          del: delay(1000),
+          timeout: delay(Math.max(0, BATCH_WINDOW - (Date.now() - batchStart))),
         });

         if (!action) continue;
         buffer.push(action);
       } catch (e) {
-        // Handle errors if needed
+        log.error("Error in captureActionsWithinPeriodTriggers:", e);
       }
     }

     if (buffer.length > 0) {
       yield put({
         type: ReduxActionTypes.TRIGGER_EVAL_BATCH,
       });
     }
   }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function* captureActionsWithinPeriodTriggers() {
while (true) {
const buffer = []; // Initialize a new buffer for each batch
const endTime = Date.now() + 10000;
// eslint-disable-next-line prefer-const
while (Date.now() < endTime) {
try {
// Use a non-blocking `take` to capture actions within the period
const { action } = yield race({
action: take(ReduxActionTypes.TRIGGER_EVAL),
del: delay(1000),
});
if (!action) continue;
buffer.push(action);
} catch (e) {
// Handle errors if needed
}
}
// After the time period, dispatch the collected actions
if (buffer.length > 0) {
yield put({
type: ReduxActionTypes.TRIGGER_EVAL_BATCH,
});
}
}
}
function* captureActionsWithinPeriodTriggers() {
while (true) {
const buffer = [];
const BATCH_WINDOW = 10000;
const batchStart = Date.now();
while (Date.now() - batchStart < BATCH_WINDOW) {
try {
const { action } = yield race({
action: take(ReduxActionTypes.TRIGGER_EVAL),
timeout: delay(Math.max(0, BATCH_WINDOW - (Date.now() - batchStart))),
});
if (!action) continue;
buffer.push(action);
} catch (e) {
log.error("Error in captureActionsWithinPeriodTriggers:", e);
}
}
if (buffer.length > 0) {
yield put({
type: ReduxActionTypes.TRIGGER_EVAL_BATCH,
});
}
}
}

@vsvamsi1 vsvamsi1 added the ok-to-test Required label for CI label Nov 27, 2024
@vsvamsi1 vsvamsi1 marked this pull request as draft November 27, 2024 18:38
@vsvamsi1
Copy link
Contributor Author

/build-deploy-preview skip-tests=true

Copy link

Deploying Your Preview: https://github.com/appsmithorg/appsmith/actions/runs/12063613461.
Workflow: On demand build Docker image and deploy preview.
skip-tests: true.
env: ``.
PR: 37762.
recreate: .

Copy link

Deploy-Preview-URL: https://ce-37762.dp.appsmith.com

Copy link

github-actions bot commented Dec 5, 2024

This PR has not seen activitiy for a while. It will be closed in 7 days unless further activity is detected.

@github-actions github-actions bot added the Stale label Dec 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ok-to-test Required label for CI Stale
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant